<template>
  <div class="comment">
    <h3>评论</h3>
    <van-field
      class="my-field"
      v-model="message"
      rows="2"
      autosize
      label="评论"
      type="textarea"
      maxlength="50"
      :placeholder="placeholder"
      show-word-limit
    />

    <van-button class="my-post" type="primary" block @click="postComment"
      >发表评论</van-button
    >

    <van-card
      v-for="(comment, index) in comments"
      :key="index"
      :desc="comment.content"
    >
      <template #thumb>
        <van-icon
          name="https://b.yzcdn.cn/vant/icon-demo-1126.png"
          class="name"
        />
        <div>
          {{ comment.user_name }}
        </div>
      </template>
      <template #title>
        <van-rate v-model="comment.rate" readonly />
      </template>
      <template #price>
        {{ comment.add_time | datefmt }}
      </template>
    </van-card>

    <van-button type="warning" block @click="getMore">{{
      moreText
    }}</van-button>
  </div>
</template>
<script>
export default {
  props: ['id'],
  data: () => ({
    message: '',
    placeholder: '说说你的看法吧',
    pageNo: 0,
    pageSize: 6,
    type: 0,
    biztype: 1,
    comments: [],
    hasMore: false
  }),
  methods: {
    // 获取评论
    async getComments() {
      // 节流
      if (this.hasMore !== false) return
      ++this.pageNo
      const res = await this.$http.getComments({ id: this.id, pageNo: this.pageNo, pageSize: this.pageSize, type: this.type, biztype: this.biztype })
      console.log(res)
      // 上一页拼接下一页的数据
      // this.comments = this.comments.concat(res.data.message)
      // 计算是否已经加载完毕
      // this.hasMore = this.pageNo * this.pageSize > res.data.count
    },
    // 发表评论
    async postComment() {
      await this.$http.postComment({ id: this.id, content: this.message })
      this.comments.unshift({
        add_time: new Date().getTime(),
        content: this.message,
        rate: 5,
        user_name: '用户'
      })
      this.message = ''
    },
    // 获取更多评论
    getMore() {
      this.getComments()
    }
  },
  computed: {
    moreText() {
      return this.hasMore ? '没有更多了' : '加载更多'
    }
  },
  created() {
    this.getComments()
  }
}
</script>
<style lang="less" scoped>
.comment {
  margin-top: 10px;
  .my-field {
    border: 1px solid #ddd;
  }
  .my-post {
    margin-top: 10px;
  }
  .name {
    font-size: 40px;
  }
  .van-card__thumb {
    height: 55px;
  }
  .van-card__content {
    min-height: 55px;
  }
}
</style>
